<template>
    <div>
        <!--对数据做查询-->
        <el-row>
            <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline">
                <el-form-item label="角色ID">
                    <el-input v-model="formInline.roleId" placeholder="角色ID"></el-input>
                </el-form-item>
                <el-form-item label="角色名称">
                    <el-input v-model="formInline.roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
                <el-button
                        type="primary"
                        @click="handleAdd">添加角色
                </el-button>
            </el-form>
        </el-row>
        <!--表格内容-->
        <el-row>
            <el-table
                    :data="tableData"
                    style="width: 100%" border>
                <el-table-column
                        prop="roleId"
                        label="角色ID"
                >
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        label="角色名称"
                >
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="角色状态"
                        :formatter="roleStatus">
                </el-table-column>
                <el-table-column
                        prop="createBy"
                        label="创建者"
                >
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="创建日期"
                >
                </el-table-column>
                <el-table-column
                        prop="updateBy"
                        label="更新者"
                >
                </el-table-column>
                <el-table-column
                        prop="updateTime"
                        label="更新时间"
                >
                </el-table-column>
                <el-table-column
                        prop="remark"
                        label="备注">
                </el-table-column>
                <el-table-column label="操作" width="280">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑信息
                        </el-button>
                        <el-button
                                size="mini"
                                @click="handleEditMenu(scope.$index, scope.row)">编辑权限
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!--分页定义-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <!--编辑或添加对话框-->
        <el-dialog
                :title="title"
                :visible.sync="addOrEditDialogVisible"
                width="30%">
            <el-form :model="editOrAddForm" ref="editOrAddForm" :rules="rules" label-width="50px"
                     class="demo-ruleForm">
                <el-input v-model="editOrAddForm.roleId" style="display: none"></el-input>
                <el-form-item label="名称" prop="roleName">
                    <el-input v-model="editOrAddForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="editOrAddForm.status">
                        <el-radio :label="`0`" border>正常</el-radio>
                        <el-radio :label="`1`" border>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editOrAddForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="closeEditOrAddDialog">取 消</el-button>
            <el-button type="primary" @click="submitEditOrAddDialog('editOrAddForm')">确 定</el-button>
        </el-dialog>
        <!--编辑角色权限对话框-->
        <el-dialog
                :title="titlea"
                :visible.sync="editDialogVisible"
                width="30%">
            <el-input :v-model="roleId" style="display: none"></el-input>
            <el-tree
                    :data="treeData"
                    :show-checkbox="true"
                    node-key="id"
                    ref="tree"
                    :props="defaultProps">
            </el-tree>
            <el-button @click="closeTreeDialog">取 消</el-button>
            <el-button type="primary" @click="submitTreeDialog()">确 定</el-button>

        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            const validateContract = (rule, value, callback) => {
                if (this.editOrAddForm.roleId === undefined) {
                    this.editOrAddForm.roleId = 0;
                }
                this.$http.get("/ss/role/checkName?roleName=" + value + "&roleId=" + this.editOrAddForm.roleId)
                    .then((response) => {
                        if (response.data.resultCode === 5000) {
                            callback(new Error('该名称已存在！'));
                        } else {
                            callback();
                        }
                    })
            };
            return {
                tableData: [],
                currentPage: 1,//当前页
                total: 100, //总数据量
                formInline: {roleName: '', roleId: ''},
                pageSize: 5,//每页数据量
                addOrEditDialogVisible: false, //对话框的状态，默认关闭
                editDialogVisible: false,
                title: '',
                titlea: '',
                true: true,
                roleId: '',
                editOrAddForm: {
                    roleId: '',
                    roleName: '',
                    status: '',
                    remark: '',
                },
                rules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                        {trigger: 'blur', validator: validateContract}//自定义验证:调方法
                    ],
                    status: [
                        {required: true, message: '请选择状态', trigger: 'blur'},
                    ],
                },
                treeData: [],//树的数据

                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
            }
        },
        // 初始化数据  mounted()
        created: function () {
            this.loadData();
        },
        methods: {
            //封装数据请求
            loadData() {
                var _this = this;
                this.$http.post("/ss/role/queryAll?pageNo=" + this.currentPage + "&pageSize=" + this.pageSize, this.formInline).then((response) => {
                    _this.tableData = response.data.t.list;
                    _this.total = response.data.t.total;

                })
            },
            //处理编辑角色信息
            async handleEdit(index, row) {
                let rowData = JSON.parse(JSON.stringify(row));
                this.editOrAddForm = {};
                this.title = '角色信息管理';
                this.editOrAddForm = rowData;
                this.addOrEditDialogVisible = true;
            },
            //处理编辑角色权限
            async handleEditMenu(index, row) {
                let rowData = JSON.parse(JSON.stringify(row));
                this.treeData = [];
                this.titlea = '角色权限管理';
                this.roleId = rowData.roleId;
                //查找全部menu
                await this.$http.get("/ss/menu/queryAllMenuTree").then((response) => {
                    this.treeData = response.data.t;
                });
                this.$http.get("/ss/menu/queryMenuIdForTreeByRoleId?roleId=" + rowData.roleId).then((response) => {
                    // 清空tree的选择
                    this.$refs.tree.setCheckedKeys([]);
                    let noHasChildrenMenuTree = response.data.t;
                    noHasChildrenMenuTree.forEach(element => {
                        // 设置数组勾选，查出来所有的菜单
                        this.$refs.tree.setChecked(element, true, false)
                    })
                });


                this.editDialogVisible = true;
            },
            //处理删除
            handleDelete(index, row) {
                let rowData = JSON.parse(JSON.stringify(row));
                this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/ss/role/deleteById?roleId=" + rowData.roleId).then((response) => {
                        if (response.data.resultCode === 2000) {
                            this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                            this.loadData();
                            this.addOrEditDialogVisible = false;
                        } else {
                            this.$message({
                                message: response.data.resultMessage,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            //处理添加
            handleAdd() {
                this.editOrAddForm = {};
                this.title = '添加角色';
                this.addOrEditDialogVisible = true;
            },
            //分页 每页数量变化时处理
            handleSizeChange(val) {
                this.pageSize = val;
                this.loadData();
            },
            //分页 第几页变化时处理
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },
            //点击查询方法
            onSubmit() {
                this.currentPage = 1;
                this.loadData();
            },
            //判断角色状态
            roleStatus(row) {
                if (row.status === "0") {
                    return "正常"
                } else {
                    return "禁用"
                }
            },
            closeEditOrAddDialog() {
                this.addOrEditDialogVisible = false;
            },
            submitEditOrAddDialog(editOrAddForm) {
                this.$refs[editOrAddForm].validate((valid) => {
                    if (valid) {
                        if (this.editOrAddForm.roleId >= 1) {
                            this.$http.put("/ss/role/update", this.editOrAddForm).then((response) => {
                                if (response.data.resultCode === 2000) {
                                    this.$message({
                                        message: '修改成功！',
                                        type: 'success'
                                    });
                                    this.loadData();
                                    this.addOrEditDialogVisible = false;
                                } else {
                                    this.$message({
                                        message: response.data.resultMessage,
                                        type: 'error'
                                    });
                                }
                            })
                        } else {
                            this.$http.post("/ss/role/insert", this.editOrAddForm).then((response) => {
                                if (response.data.resultCode === 2000) {
                                    this.$message({
                                        message: '添加成功！',
                                        type: 'success'
                                    });
                                    this.loadData();
                                    this.addOrEditDialogVisible = false;
                                } else {
                                    this.$message({
                                        message: response.data.resultMessage,
                                        type: 'error'
                                    });
                                }
                            })
                        }

                    } else {
                        return false;
                    }
                });
            },
            //重置表单
            resetForm() {
                this.formInline = {};
                this.loadData();
            },
            closeTreeDialog() {
                this.editDialogVisible = false;
            },
            //提交修改角色权限
            submitTreeDialog() {
                let arr = [];
                arr.push(...this.$refs.tree.getCheckedKeys());
                arr.push(...this.$refs.tree.getHalfCheckedKeys());
                let roleData = {
                    roleId: this.roleId,
                    arr: arr
                };
                this.$http.post("/ss/roleMenu/insert", roleData).then((response) => {
                    if (response.data.resultCode === 2000) {
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                        this.loadData();
                        this.addOrEditDialogVisible = false;
                    } else {
                        this.$message({
                            message: response.data.resultMessage,
                            type: 'error'
                        });
                    }
                });
                this.editDialogVisible = false;
            }

        }
    }
</script>
<style>

</style>